package org.dfl.plugin.autoalign;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.dfl.plugin.DflPlugin;

/**
 * Class that install graphiz in user home directory
 * @author Piotr Wlodarczyk
 *
 */
public class GraphvizInstaller {
	
	/**
	 * copy graphviz files to user home directory
	 */
	public static void installGraphviz() {
		String dotLocation = "dot";
		String os = System.getProperty("os.name");
		if (os.startsWith("Windows")) {
			createDirectories();
			
			loadFile("freetype6.dll");
			loadFile("jpeg.dll");
			loadFile("libexpat.dll");
			loadFile("png.dll");
			loadFile("z.dll");
			loadFile("zlib1.dll");
			dotLocation = loadFile("dot.exe");
		}
		;

		System.setProperty("dflplugin.dotLocation", dotLocation);
	}
	
	
	/**
	 * Creates project directories
	 */
	private static void createDirectories() {
		File appHome;
		String application = "DflPlugin";
		String homeString = System.getProperty("user.home");
		File home = new File(homeString);
		String os = System.getProperty("os.name");
		if (os.equals("Mac OS X")) {
			System.setProperty("separator", "/");
			File libDir = new File(home, "Library/Application Support");
			libDir.mkdirs();
			appHome = new File(libDir, application);
		} else if (os.startsWith("Windows")) {
			System.setProperty("separator", "\\");
			String APPDATA = System.getenv("APPDATA");
			File appData = null;
			if (APPDATA != null) {
				appData = new File(APPDATA);
			}
			if (appData != null && appData.isDirectory()) {
				appHome = new File(appData, application);
			} else {
				appHome = new File(home, application);
			}
		} else {
			System.setProperty("separator", "/");
			// We'll assume UNIX style is OK
			appHome = new File(home, "." + application.toLowerCase());
		}

		if (!appHome.exists()) {
			if (appHome.mkdir()) {
				System.out.println("Created home directory");
			} else {
				System.out.println("Unable to create home directory");
				return;
			}
		}

		// create dot files folder
		File dotfiles = new File(appHome, "dotFiles");
		if (!dotfiles.exists())
			dotfiles.mkdir();

		System.setProperty("dflplugin.dotFiles", dotfiles.getAbsolutePath());
	}

	private static String loadFile(String name) {
		File f = null;
		try {
			InputStream in = DflPlugin.getURLFromPlugin(name).openStream();
			f = new File(System.getProperty("dflplugin.dotFiles")
					+ System.getProperty("separator") + name);
			if (f.exists())
				return f.getAbsolutePath();

			BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(f));
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			out.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}

		return f.getAbsolutePath();
	}
}
